﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Text;

namespace CNative.DbUtils.Helpers
{
    internal static class DbConnectionExtensions
    {

        static DbCommand PingCommand(DbConnection conn, string commandText = "select 1")
        {
            var cmd = conn.CreateCommand();
            cmd.CommandTimeout = 5;
            cmd.CommandText = commandText;
            return cmd;
        }
        public static bool Ping(this DbConnection that, string commandText = "select 1", bool isThrow = false)
        {
            try
            {
                using (var cmd = PingCommand(that, commandText))
                {
                    cmd.ExecuteNonQuery();
                    return true;
                }
            }
            catch (Exception ex)
            {
                if (that.State != ConnectionState.Closed) try { that.Close(); } catch { }
                if (isThrow) throw ex;
                return false;
            }
        }
#if NET40
#else
        async public static System.Threading.Tasks.Task<bool> PingAsync(this DbConnection that, string commandText = "select 1", bool isThrow = false)
        {
            try
            {
                using (var cmd = PingCommand(that, commandText))
                {
                    await cmd.ExecuteNonQueryAsync();
                    return true;
                }
            }
            catch (Exception ex)
            {
                if (that.State != ConnectionState.Closed) try { that.Close(); } catch { }
                if (isThrow) throw ex;
                return false;
            }
        }
#endif
    }
}
